import React from 'react';
import { message, Drawer } from 'antd';
import { broadcast, listen } from '@zny/utils';
import { STATE_CHANGED } from '@zny/hooks';
import microApp from '@/utils/microApp';

interface IBaseProps {
  location: any;
}
export default class extends React.Component<IBaseProps> {
  state = {
    Component: null,
    compProps: {},
    visible: true,
  };

  private storeKey;

  componentDidMount() {
    console.log(this.props, 'Base componentWillMount');
    const context = require.context('./', true, /\/form\.tsx?$/);
    const formDict = context.keys().reduce((res, key) => {
      let match = key.match(/.\/(.*?)\/form.tsx/);
      match && match[1] && (res[match[1].toLocaleLowerCase()] = context(key));
      return res;
    }, {});

    const pathname = microApp.get('pathname');
    const compName = microApp.get('compName');
    const compProps = microApp.get('compProps');
    console.log('pathname', pathname);
    if (!pathname) {
      return;
    }
    const routeKey = `${pathname
      .split('/')
      .slice(1)
      .join('/')}`.toLocaleLowerCase();
    const formKey = Object.keys(formDict).reduce((res, key) => {
      if (key.startsWith(routeKey)) {
        return key;
      }
      if (routeKey.startsWith(key) && key.length > res.length) {
        return key;
      }
      return res;
    }, '');
    console.log(
      'Base',
      formDict,
      formKey,
      compName,
      formDict[formKey],
      formDict[formKey] && formDict[formKey][compName],
    );
    if (formDict[formKey] && formDict[formKey][compName]) {
      this.setState({
        Component: formDict[formKey][compName],
        compProps,
      });
    } else {
      message.error(`组件路径不正确，请确认：${pathname}`);
      this.setState({}, () => broadcast('hideWorkflowForm'));
    }

    const { bus, mountId } = microApp.get();
    this.storeKey = `${mountId}::props::update`;
    console.log(this.storeKey, 'storeKey');

    bus.on(this.storeKey, this.handleReceiveProps);
  }

  componentWillUnmount() {
    const { bus } = microApp.get();
    bus && bus.off(this.storeKey, this.handleReceiveProps);
    broadcast('hideWorkflowForm');
  }

  handleReceiveProps = (compProps: any) => {
    this.setState({
      compProps,
    });
  };

  handleHideForm = () => {
    const {
      compProps: { onClose },
    } = this.state;
    const preventClose = (onClose && onClose()) === false;
    if (preventClose) {
      return;
    }
    this.setState({ visible: false });
    broadcast('hideWorkflowForm');
  };

  render() {
    const { Component, compProps = {}, visible } = this.state;
    if (!Component) {
      return <i title="no component"></i>;
    }
    const type = microApp.get('type');
    if (type === 'workflowForm') {
      return (
        <Component
          type="drawer"
          visible={visible}
          {...compProps}
          onClose={this.handleHideForm}
        />
      );
    }
    return (
      <Drawer
        maskClosable={false}
        destroyOnClose
        mask={false}
        visible={visible}
        width={compProps.width}
        {...compProps.drawerProps}
        afterVisibleChange={visible => !visible && this.handleHideForm()}
        onClose={this.handleHideForm}
      >
        <Component {...compProps} />
      </Drawer>
    );
  }
}
